package com.xxx.controller;

import com.xxx.pojo.Admin;
import com.xxx.pojo.AdminLoginParam;
import com.xxx.pojo.RespBean;
import com.xxx.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 * @author WXH
 * @version 1.0
 * @date 2022/2/23 18:46
 */
@Api(tags = "用户登录")
@RestController
public class LoginController {
    //注入servers
    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        //登陆验证

        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request
        );
    }
    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        if (principal == null){
            return null;
        }
        //获取用户名
        String username = principal.getName();
        //获取完整用户对象
        Admin admin=adminService.getAdminByUserName(username);
        //设置用户角色
        admin.setRoles(adminService.getRoles(admin.getId()));
        admin.setPassword(null);

        return admin;
    }





    //前端设置退出功能，后端给一个接口
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.sucess("注销成功");
    }
}
